import { Component } from '@angular/core';

import { Events, NavController, AlertController, Platform, ModalController, App } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../../login/login.component';
import { SettingIndexService } from './index.service';
import { LocalNotifications } from '@ionic-native/local-notifications';

import { SettingNotePage } from '../note/note.component';
import { SettingFeedbackPage } from '../feedback/feedback.component';
import { SettingSealPage } from '../seal/seal.component';

import { Common } from '../../../providers/common';
import { Config } from '../../../providers/config';

import { LockPage } from '../../lock/lock.component';
import _ from "lodash";
import { SettingPushPage } from "../push/push.component";

@Component({
	selector: 'page-setting-index',
	templateUrl: 'index.html',
	providers: [SettingIndexService]
})
export class SettingIndexPage {
	moa_page_name: any = "page-setting-index";
	moa_page_explain: any = "系统设置";

	userInfo: any = {};

	isHasPushPermission = false;
	// 定义是否允许推送
	isPush = false;
	// 是否开启手势密码
	isEnableGesturePassword = false;

	// 是否显示有新版本更新
	isShowNewVersion = false;

	pushTypeList = [];

	new_empphoto = '';

	constructor(
		public nav: NavController,
		public setttingIndexService: SettingIndexService,
		public alertCtrl: AlertController,
		public platform: Platform,
		public modalCtrl: ModalController,
		public common: Common,
		public events: Events,
		public appCtrl: App,
		public config: Config,
		public storage: Storage,
    private localNotifications: LocalNotifications
	) {
		let that = this;
		this.init();
	}

	init() {
		let that = this;
		this.storage.get('userInfo').then(function (userInfo) {
			console.log("userInfo>>>>>>", userInfo);
			if (userInfo) {
				that.userInfo = userInfo;
				that.isPush = userInfo.isPush;

				if (userInfo.empphoto && (_.endsWith(userInfo.empphoto, 'jpeg') || _.endsWith(userInfo.empphoto, 'jpg') || _.endsWith(userInfo.empphoto, 'bmp') || _.endsWith(userInfo.empphoto, 'gif'))) {
					that.storage.get('id_token').then((token) => {
						that.new_empphoto = that.config.server + "api/v1/common/img?access_token=" + token + "&url=" + userInfo.empphoto + "&resize=true";
					});
				}
				/*if (userInfo.subPush) {
				  that.pushTypeList = userInfo.subPush;
				  console.log("pushTypeList>>>>>>>>>", that.pushTypeList);
        } else {
				  that.storage.get("configs").then(configs => {
				    let push_config = _.find(configs, {name: "push_config"});
				    if (push_config) {
				      that.userInfo.subPush = push_config["json"];
              that.pushTypeList = that.userInfo.subPush;
				      that.storage.set("userInfo", that.userInfo);
            }
          });
        }*/
			}
		});
		this.storage.get('lockPassword').then((lockPassword) => {
			if (lockPassword) {
				this.isEnableGesturePassword = true;
			}
		});
	}

	/**
	 * [goPage 跳转页面]
	 * @param {[type]} type [description]
	 */
	goPage(type) {
		let page: any;
		if (type == 'note') {
			page = SettingNotePage;
		} else if (type == 'feedback') {
			page = SettingFeedbackPage;
		}
		else if (type == 'seal') {
			page = SettingSealPage;
		} else if (type === "push") {
			page = SettingPushPage;
		}
		this.nav.push(page);
	}

	/**
	 * [logout 退出登录]
	 */
	logout() {
		let that = this;
		let prompt = this.alertCtrl.create({
			title: '提示',
			message: "安全退出之后会清除缓存、清除手势密码、不再接收推送，确认是否退出？",
			buttons: [
				{
					text: '取消',
					handler: data => {
						console.log('Cancel clicked');
					}
				},
				{
					text: '确认',
					handler: data => {
            that.localNotifications.clearAll();

						that.setttingIndexService.logout().subscribe(data => {
							if (data) {

								that.storage.remove("indexAuthority");

								that.storage.remove('lockPassword');
								that.storage.remove('myMenu');
								that.storage.remove('selected-home-page');
								that.storage.remove('id_token').then(() => {
									that.appCtrl.getRootNav().setRoot(LoginPage);
									that.common.removeDownloadAttach(true);
								});
								if (window['socketio']) {
									window['socketio'].close();
								}
							}
						});


					}
				}
			]
		});
		prompt.present();

	}

	ionViewDidEnter() {
		console.log('-------ionViewDidEnter--PushNotification--hasPermission--------------');
		let that = this;
		if (window['PushNotification'] && this.platform.is('ios')) {
			window['PushNotification'].hasPermission(function (data) {
				if (!data.isEnabled) {
					that.isHasPushPermission = false;
				} else {
					that.isHasPushPermission = true;
				}
			});
		} else {
			that.isHasPushPermission = true;
		};

		that.isShowNewVersion = false;

		this.common.getVersionInfo().then((currentVersion: any) => {
			that.storage.get("newVersionInfo").then((newVersion: any) => {
				if (newVersion) {
					if (newVersion.type == 'html5' && newVersion.name !== currentVersion.h5Version) {
						that.isShowNewVersion = true;
					}

					if ((newVersion.type == 'ios' || newVersion.type == 'android') && newVersion.name !== currentVersion.appVersion) {
						that.isShowNewVersion = true;
					}
				}
			});
		});

	}

	onChangeGestureStatus($event) {
		console.info($event);
		let that = this;
		if ($event.checked) {
			this.storage.get('lockPassword').then((lockPassword) => {
				if (!lockPassword) {
					let modal = this.modalCtrl.create(LockPage, {});
					modal.present();
					modal.onWillDismiss((data: any[]) => {
						console.info(data);
						$event.checked = data['isSet'] ? true : false;
					});
				}
			});
		} else {
			this.storage.remove('lockPassword').then(() => {
				$event.checked = false;
			});
		}
	}

	onChangePushStatus($event) {
		let that = this;
		// 判断如果要请求的状态和服务器的状态一致，则不提交
		this.storage.get('userInfo').then(function (userInfo) {
			if ($event.checked == userInfo.isPush) {
				return;
			}
			if ($event.checked && !that.isHasPushPermission) {
				let alert = that.alertCtrl.create({
					title: '提示',
					subTitle: '请先在系统设置--通知--广发办公--开启消息通知',
					buttons: ['确认']
				});
				alert.present();
				$event.checked = false;
				// setTimeout(function() {
				that.isPush = false;
				// }, 3000);
				return false;
			}

			that.storage.get('registrationId').then(function (registrationId) {
				console.log('----------------registrationId--------------');
				console.log(registrationId);
				that.setttingIndexService.changePushStatus($event.checked, that.userInfo.subPush, registrationId).subscribe(data => {
					if (data) {
						// let alert = that.alertCtrl.create({
						// 	title: '提示',
						// 	subTitle: '修改成功',
						// 	buttons: ['确认']
						// });
						// alert.present();
						that.userInfo.isPush = $event.checked;
						that.isPush = $event.checked;
						$event.checked = that.userInfo.isPush;
						that.storage.set('userInfo', that.userInfo);
					} else {
						that.isPush = !$event.checked;
						$event.checked = that.isPush;
					}
				});
			});
		});
	}

	onChangeSubPushStatus($event, item) {
		let that = this;
		// 判断如果要请求的状态和服务器的状态一致，则不提交
		this.storage.get('userInfo').then(function (userInfo) {

			if (item) {
				_.forEach(that.pushTypeList, type => {
					if (type["pushType"] === item["pushType"]) {
						type["isPush"] = $event.checked;
					}
				});
			}

			that.storage.get('registrationId').then(function (registrationId) {
				console.log('----------------registrationId--------------');
				console.log(registrationId);
				that.setttingIndexService.changePushStatus(that.isPush, that.pushTypeList, registrationId).subscribe(data => {
					if (data) {
						that.userInfo.subPush = that.pushTypeList;
						that.storage.set('userInfo', that.userInfo);
					} else {
						that.isPush = !$event.checked;
						$event.checked = that.isPush;
					}
				});
			});
		});
	}

	// 清理缓存
	cleanStore() {
		let that = this;
		let prompt = this.alertCtrl.create({
			title: '提示',
			message: "是否清除所有缓存？",
			buttons: [
				{
					text: '取消',
					handler: data => {
						console.log('Cancel clicked');
					}
				},
				{
					text: '确认',
					handler: data => {
						that.common.removeDownloadAttach();
					}
				}
			]
		});
		prompt.present();
	}

	// 检查更新
	checkUpdate() {
		this.common.checkUpdate({
			isShowLoading: true,
			isAlterTips: true
		});
	}
}
